// var SDK = require('../../../sdk/NIM_Web_SDK_v3.8.0-beta.js')
import { getOptions, getInstance } from '../../../utils/im.js'
import util from '../../../utils/util.js'
import emojiObj from '../emoji.js'
import cache from '../../../utils/cache.js'
// import userInfo from '../modelUserInfo.js'
var currentScrollTop;
// var userInfo = this.userInfo;
Page({
  inputValue: '', // 输入内容
  data: {
    bottomHidden: false, // hack手法解决瞬移到底部问题
    isP2p: false,
    isCustomService: false,
    scrollTop: 0, // 距离顶部高度
    scrollIntoView: '', // 滚到底部
    currentPage: 1, // 当前页,
    isLoading: false, // 是否正在加载
    pageSize: 10, // 每次滚动加载量
    isGroupTalk: false, // 是否为群聊
    canCall: false, // 是否允许通话
    wholeSession: null, // 整条会话信息
    sessionId: '', // sessionId
    inputValue: '', // 输入内容
    showSendBtn: false, // 是否展示发送按钮
    defOptions: null,
    chatIsOver: false, // 订单是否已经结束
    openEmojiModule: false, // 开启表情功能模块
    openExtendModule: false, // 开启扩展功能模块
    emojiArr: [],
    cs: null, // 患者信息(群聊)
    order_no: '', // 订单编号
    avatar: null, // p2p对方头像(单聊)
    msgList: [] // 消息列表(时间格式改变后的) [本地存储里面有原样的]
  },
  closeModule: function() {
    this.setData({
      openExtendModule: false,
      openEmojiModule: false
    })
  },
  openEmoji:function(e) {
    this.setData({
      openEmojiModule: !this.data.openEmojiModule,
      openExtendModule: false
    })
  },
  openExtend:function (e) {
    this.setData({
      openEmojiModule: false,
      openExtendModule: !this.data.openExtendModule
    })
  },
  bindKeyInput: function (e) {
    if (e.detail.value || e.detail.value.trim()) {
      this.inputValue = e.detail.value;
      if (!this.data.showSendBtn) {
        this.setData({
          inputValue: e.detail.value,
          showSendBtn: true
        })
      }
    } else {
      this.inputValue = e.detail.value;
      this.setData({
        inputValue: e.detail.value,
        showSendBtn: false
      })
    }
  },
  sendMessage1: function () { // 点击发送消息
    var me = this
    wx.nim.sendText({
      scene: this.data.wholeSession.scene,
      to: this.data.wholeSession.to,
      text: this.inputValue,
      done: function (error, msg) {
        me.sendMsgDone(error, msg)
      }
    })
    this.inputValue = '' // 发送信息以后清空
  },
  updateDom: function (msg) {
    // 本地存储改变
    var wholeSession = this.data.wholeSession
    var oldMsgList = wholeSession.msgs
    var newMsgList = wx.nim.mergeMsgs(oldMsgList, msg)
    wholeSession.msgs = newMsgList;
    this.setData({
      msgList: this.msgListInit(newMsgList),
      wholeSession: wholeSession,
      inputValue: '',
      showSendBtn: false,
      openEmojiModule: false,
      openExtendModule: false
    })
  },
  sendMsgDone: function (error, msg) {
    console.log(error);
    console.log(msg);
    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg.idClient);
    if (this.data.orderId) { // 订单聊天则发送
      this.saveMsg(msg);
    }
    this.updateDom(msg);
  },
  // 给admin发送消息记录保存
  saveMsg: function (msg) {
    var orderListData = {};
    if(msg.type === 'image'){
      orderListData.msg_type = '1'
    }
    if(msg.type === 'file'){
      orderListData.msg_type = '6'
    }
    if(msg.type === 'text'){
      orderListData.msg_type = '0'
    }
    orderListData.file = msg.file
    orderListData.type = 3
    orderListData.from = msg.from
    orderListData.text = msg.text
    orderListData.time = msg.time
    orderListData.to = msg.to 
    orderListData.order_id = this.data.orderId
    orderListData.message_id = msg.idClient
    wx.request({
      url: wx.envConfig.adminHost + '/source/saveMsg',
      method: 'POST',
      data: orderListData,
      success: function(res) {
        console.log('res',res)
      }
    })
  },
  emojiClick:function(e) { // 表情点击之后
    var text = e.currentTarget.dataset.text;
    this.inputValue = this.inputValue + text;
    this.setData({
      inputValue: this.inputValue,
      showSendBtn: true
    })
  },
  createEmojiArr: function () { // 生成表情数组
    var arr = []
    for (var i = 0; i < 116; i++) {
      if (i > 0 && i < 10 ) {
        i = '0' + i
      }
      for (let [key, value] of Object.entries(emojiObj)) {
        if (value === 'emoji_' + i + '.png') {
          arr.push({url:'../../../resource/icon/emoji/emoji_' + i + '.png', text: key})
        }
      }
    }
    this.setData({
      emojiArr: arr
    })
  },
  imgError(e) {
    console.log('图片出不来', e);
  },
  msgListInit (msgList) { // 处理消息展示方式
    msgList = this.controlRender(msgList) // 控制展示
    var copyList = util.deepCopy(msgList)
    // 过滤信息(仅消息跟入群信息支持查看)

    if (this.role == 3) { // 订单群聊(基本信息+入群信息)
      copyList = copyList.filter(item => {
        if (item.attach && item.attach.team && item.attach.team.serverCustom) {
          if (JSON.parse(item.attach.team.serverCustom).state == 1) { // 订单聊天已经结束判断
            this.setData({
              chatIsOver: true
            })
          }
        }
        return (item.type != 'notification' || (item.attach && item.attach.type == 'addTeamMembers'))
      }) 
    } else { // 单聊与在线客服(仅支持 基本信息)
      copyList = copyList.filter(item => {// 过滤通知信息
        return item.type != 'notification'
      }) 
    }
    copyList.forEach((el) => {
        // 区分文件的类型
        if (el.type == 'text') {
          if (/\[[^\]]*\]/.test(el.text)) { // 过滤表情
            el.nodes = []
            var temp = []
            var arr = [] // 表情数组
            var tpl = el.text.replace(/\[[^\]]*\]/g, function (matchItem) {
              for (let [key, value] of Object.entries(emojiObj)) {
                if (key === matchItem) {
                  temp.push(key) // 记录存储
                  arr.push(wx.envConfig.host + '/static/emoji/' + value)
                }
              }
              if (temp.findIndex(it => {
                return it == matchItem
              }) == -1) { // 不在表情数组内
                return matchItem
              }
              return '<%%>'
            })
            var splitArr = tpl.split('<%%>') // 文字数组
            arr.forEach((item, index) => {
              el.nodes.push({type: 'text', text: splitArr[index]})
              el.nodes.push({name: 'img', attrs: {src: arr[index], style: 'height:60rpx;'}})
            })
            el.nodes.push({type: 'text', text: splitArr[splitArr.length - 1]})
          } else {
            el.nodes = [{type: 'text', text: el.text}]
          }
        }
        if (el.type == 'image') {
          el.nodes = [{name: 'img', attrs: {src: el.file.url, style: 'width: 100%;display:inline-block;'}}]
        }
        if (el.type == 'file') {
          el.nodes = [{name:'div', attrs: {style: 'text-decoration: underline'}, children: [{type: 'text',text: el.file.name}]}]
        }
        if (el.scene == 'p2p' && el.from == this.userInfo.accid) { // 只支持p2p查询消息
          el.isRead = wx.nim.isMsgRemoteRead(el)
        }
        if (el.scene == 'team' && el.type == 'notification') { // 通知消息
          // 存储当前群信息
          var notifyType = el.attach.type
          var isMe = el.from === this.userInfo.uid
          var str = ''
          switch (notifyType) {
            case 'addTeamMembers':
            var arrTemp = el.attach.users.filter(it => {
              return el.attach.accounts.indexOf(it.account) > -1
            });
            arrTemp.map((i,idx) => {
              if (idx != arrTemp.length - 1) {
                str = str + i.nick + ','
              } else {
                str = str + i.nick
              }
            });
            el.nofityStr = str + '加入群';
            break;
            case 'removeTeamMembers':
            break;
            case 'leaveTeam':
            break;
            case 'updateTeam':
            el.nofityStr = '群信息更新'
            break;
            case 'acceptTeamInvite':
            // 入群邀请
            break;
            case 'passTeamApply':
            break;
            default:
            el.nofityStr = '收到群消息,小程序暂不支持查看';
          }
        }
        if (el.scene == 'team' && el.type == 'custom') { // 自定义消息
          var contents = JSON.parse(el.content)
          if (contents.type == 21) { // 21通话结束
            el.nodes = [{name: 'img', attrs: {src: wx.envConfig.host + '/static/images/call-img.png', style: 'width: 15px;margin-right:10px;'}}, {type: 'text', text: '通话时长'},
            {type: 'text', text: parseInt(+contents.duration/60) + ':' + parseInt(+contents.duration%60)}]
          }
          if (contents.type == 20) { // 20未接听
            el.nodes = [{name: 'img', attrs: {src: wx.envConfig.host + '/static/images/call-img.png', style: 'width: 15px;margin-right:10px;'}}, {type: 'text', text: '未接听'}]
          }
          if (contents.type == 5) { // 5 手术设计方案
            el.nodes = [{name:'span', attrs: {style: 'text-decoration: underline'}, children: [{type: 'text',text: contents.title}]}, {type:'text', text:'(请查看)'}]
          }
        }
        if (el.scene == 'team') {
          // console.log('el', el)
          if (this.teamMembers && this.teamMembers.length) {
            var match = this.teamMembers.filter(it => {
              return it.account == el.from
            })[0]
            var custom = match && match.custom && JSON.parse(match.custom)
            var uType = custom && custom.u_type
            el.identity = uType == 1 ? '手术设计师' :
                            uType == 4 ? '分割设计师' :
                              uType == 0 ? (custom.type == 0 && '医生') || (custom.type == 2 && '医学生') :
                                uType == 5 ? '客服人员' : ''
            el.avatar = (uType == 1 || uType == 4) ? '../../../resource/icon/default/designer.png' :
                          uType == 0 ? '../../../resource/icon/default/doctor.png' :
                uType == 5 ? '../../../resource/icon/default/kf-avatar.png' : '../../../resource/icon/default/designer.png'
          }
        }
        el.time = util.parseTime(el.time, '{y}年 {m}月{d}日 {h}:{i}')
    })
    console.log('copyList', copyList)
    return copyList
  },
  getTeamMembers (teamId) { // 根据群id获取群成员
    var me = this
    return new Promise((resolve, reject) => {
      wx.nim.getTeamMembers({
        teamId: teamId,
        done: function(error, obj) {
          if (!error) {
            console.log('obj',obj)
            var accounts = obj.members.map(o => {
              return o.account
            })
            me.getUserByAccount(accounts).then(users => {
              resolve(users)
            })
          }
        }
      })
    })
  },
  getUserByAccount (accounts) { // 根据群成员account获取群信息
    return new Promise((resolve, reject) => {
      wx.nim.getUsers({
        accounts:accounts,
        done: function(error, users) {
          resolve(users)
        }})
    });
  },
  contentClick: function (e) { // 消息文本点击处理
    var type = e.currentTarget.dataset.type
    var info = e.currentTarget.dataset.info
    console.log('type', type)
    console.log('info', info)
    if (type == 'file') { // 文件
      wx.downloadFile({
        url: info.file.url,
        success: function(res) {
          console.log('res', res)
          if (res.statusCode === 200) {
            wx.openDocument({ // 有效值 doc, xls, ppt, pdf, docx, xlsx, pptx
              filePath: res.tempFilePath,
              success: function (res) {
                console.log('打开文件成功')
              },
              complete: function () {
                console.log('执行了')
              }
            })
          }
        }
      })
    }
    if (type == 'image') {
      wx.previewImage({
        urls: [info.file.url]
      })
    }
    if (type == 'custom') {
      if (info.content) {
        let content = JSON.parse(info.content)
        if (content.type == 5) { // 方案设计
          wx.navigateTo({
            url: '../../order/orderDetail/orderDetail?id=' + this.data.orderId
          })
        }    
      }
    }
  },
  uploadPhoto () { // 照片上传
    var me = this
    wx.chooseImage({
      sourceType: ['album'],
      success: function (tempFilePaths) {
        //返回图片的本地文件路径列表
        console.log('tempFilePaths', tempFilePaths)
        var backUrl = tempFilePaths.tempFiles[0].path
        wx.showLoading({title: '正在上传', mask: true})
        // 图片模板{/:img_${url}:/} 发送消息
        wx.nim.sendFile({
          scene: me.data.wholeSession.scene,
          to: me.data.wholeSession.to,
          type: 'image',
          wxFilePath: backUrl,
          uploadprogress: function (obj) {
            console.log('文件总大小: ' + obj.total + 'bytes');
            console.log('已经上传的大小: ' + obj.loaded + 'bytes');
            console.log('上传进度: ' + obj.percentage);
            console.log('上传进度文本: ' + obj.percentageText);
          },
          uploaddone: function(error, file) {
              console.log('上传' + (!error?'成功':'失败'), error, file);
              wx.hideLoading()
              if (!error) {
                wx.showToast({
                  icon: 'success',
                  title: '上传成功'
                })
              } else {
                wx.showToast({
                  icon: 'fail',
                  title: '上传失败了，请检查您的网络'
                })
              }
          },
          beforesend: function(msg) {
              console.log('正在发送p2p image消息, id=' + msg.idClient);
              // me.pushMsg(msg);
          },
          done: function (error, msg) {
            me.sendMsgDone(error, msg)
          }
        })
      },
      fail: function () {

      }
    })
  },
  takePhoto () { // 拍照
    var me = this
    wx.chooseImage({
      sourceType: ['camera'],
      success: function (tempFilePaths) {
        //返回图片的本地文件路径列表
        console.log('tempFilePaths', tempFilePaths)
        var backUrl = tempFilePaths.tempFiles[0].path
        // // 图片模板{/:img_${url}:/} 发送消息
        wx.nim.sendFile({
          scene: me.data.wholeSession.scene,
          to: me.data.wholeSession.to,
          type: 'image',
          wxFilePath: backUrl,
          uploadprogress: function (obj) {
            console.log('文件总大小: ' + obj.total + 'bytes');
            console.log('已经上传的大小: ' + obj.loaded + 'bytes');
            console.log('上传进度: ' + obj.percentage);
            console.log('上传进度文本: ' + obj.percentageText);
          },
          uploaddone: function(error, file) {
              console.log('上传' + (!error?'成功':'失败'), error, file);
          },
          beforesend: function(msg) {
              console.log('正在发送p2p image消息, id=' + msg.idClient);
              // me.pushMsg(msg);
          },
          done: function (error, msg) {
            me.sendMsgDone(error, msg)
          }
        })
      },
      fail: function () {
        console.log('拍照调不起来')
      }
    })
  },
  launchCall () { // 通话
    var orderId = this.data.orderId
    var callUid = this.userInfo.uid
    var designId = this.data.designId
    wx.showActionSheet({
      itemList: ['语音通话(免费，免流量)'],
      success: function(res) {
        if (res.tapIndex === 0) {
          console.log('orderId', orderId)
          console.log('callUid', callUid)
          console.log('recUid', designId)
          wx.navigateTo({
            url: '../phone/phone?orderId=' + orderId + '&callUid=' + callUid + '&recUid=' + designId
          })
        }
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },
  doneReceiveMsg (params) { // 收到消息后的处理
    // 判断是否为本会话
    if (params.msg.sessionId == this.data.sessionId) { // 更新消息列表

      let wholeSession = this.data.wholeSession
      let newMsgList = wx.nim.mergeMsgs(wholeSession.msgs, params.msg) // 合并消息
      wholeSession.msgs = newMsgList // 覆盖新的消息

      this.setData({
        wholeSession: wholeSession,
        msgList: this.msgListInit(newMsgList)
      })
      this.caculateDynamicHeight();
    }
  },
  controlRender (list) { // 控制渲染，每次5个
    let pageSize = this.data.pageSize
    let currentPage = this.data.currentPage
    let total = list.length
    if (total > 5) {
      if (total > pageSize*currentPage) {
        return list.slice(total - pageSize*currentPage,total)
      } else {
        return list.slice(0, total)
      }
    } else {
      return list
    }
  },
  bindscrolltoupper (e) {
    // 查看更多历史记录
    console.log('isLoading', this.data.isLoading)
    if (this.data.isLoading) return
    var me = this

    var wholeSession = this.data.wholeSession // 拿到会话
    var msgList = (wholeSession && wholeSession.msgs) || []  // 拿到总的会话消息
    console.log('下拉')
    if (msgList && msgList.length > this.data.msgList.length) { // 还有未加载
      this.setData({
        currentPage: this.data.currentPage + 1,
        isLoading: true
      })
      wx.showLoading({
        title: '正在加载内容...',
        mask: true
      })
      console.log('e', e.target)
      var previousHeight
      var currentHeight
      this.queryMultipleNodes('.container').then(res => {
        console.log('res1', res[0].height)
        previousHeight = res[0].height
        this.setData({
          msgList:this.msgListInit(msgList)
        })
        this.queryMultipleNodes('.container').then(res => {
          console.log('res2', res[0].height)
          currentHeight = res[0].height
          console.log('scrollTop', currentScrollTop)
          console.log('currentHeight', currentHeight)
          console.log('previousHeight', previousHeight)
          console.log('totalScroll', currentHeight - previousHeight + currentScrollTop)
          var totalScroll = currentHeight - previousHeight + currentScrollTop - 30
          this.setData({
            scrollTop: totalScroll
          })
          setTimeout(function(){
            wx.hideLoading()
            me.setData({
              isLoading: false
            })
          }, 700)
        })
      })
    }
  },
  // 查询节点信息
  queryMultipleNodes: function(selector){
    var me = this
    var query = wx.createSelectorQuery()
    query.select(selector).boundingClientRect()
    query.selectViewport().scrollOffset()
    return new Promise((resolve, reject) =>{
      query.exec(function(res) {
        resolve(res)
        res[0].top       // selector节点的上边界坐标
        res[1].scrollTop // 显示区域的竖直滚动位置
      })
    })
  },
  getOrderDetailByOrderId: function (orderId) {
    var me = this
    wx.request({
      url: wx.envConfig.host + '/order/findByOrder?params=' + JSON.stringify({order_id: orderId}), //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
      },
      header: {
          'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        // 若设计者designUid不存在，则关闭通话功能
        if (!res.data.datas.serviceInfo || (res.data.datas.serviceInfo && res.data.datas.serviceInfo.user_designer_uid == null)) {
          me.setData({
            canCall: false
          })
        } else {
          me.setData({
            canCall: true
          })
        }
        me.setData({
          order_no: res.data.datas.serviceInfo ? res.data.datas.serviceInfo.order_no : '',
          designId: res.data.datas.serviceInfo ? res.data.datas.serviceInfo.user_designer_uid : '' // 拿到designId
        })
        console.log('数据呢,', res.data.datas)
      }
    })
  },
  getMsgFromIMServer(scene, to) {
    var promise = new Promise((resolve,reject) => {
      wx.nim.getHistoryMsgs({
        scene: scene,
        to: to,
        done: function (error, obj) {
          obj.msgs.reverse();
          resolve(obj);
          console.log('获取云端历史记录',obj);
        }
      });
    })
    return promise
  },
  distributeServer () { // 分配客服 // 注册成功但认证等待时候需要手动分配客服
    return new Promise((resolve, reject) => {
      wx.request({ 
        url: wx.envConfig.host + '/user/requestServer?cookiez=' + wx.getStorageSync('cookiez'),
        method: 'POST',
        success: (res) => {
          console.log('res', res)
          wx.setStorageSync("userInfo", res.data.datas)
          resolve()
        },
        fail: (err) => {
          console.log('err', err)
        }
      })
    })
  },
  isWorkingDuration () { // 是否在工作期间
    var now = new Date();
    if (now.getDay() == 6 || now.getDay() == 0 || now.getHours() < 9 || now.getHours() >= 18) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmText:'知道了',
        confirmColor:'#4825BF',
        content: '客服上班时间为工作日09:00-18:00,目前无法及时回复，请谅解',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    } else {
      wx.request({
        url: wx.envConfig.host + '/order/sendServerAutoReply?cookiez=' + wx.getStorageSync('cookiez') + '&params=' + JSON.stringify({
          user_id: this.userInfo.id
        }),
        method: 'POST',
        success: (res) => {
          console.log('res', res)
        },
        fail: (err) => {
          console.log('err', err)
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.userInfo = wx.getStorageSync('userInfo')
    // 为优化性能每次渲染5条
    console.log('options',options)
    // 设置role表示身份 1 客服 2单聊 3群聊
    if (!options.id) { // 在线客服
      console.log('进来了')
      // 判断客服上班时间
      this.role = 1;
      wx.setNavigationBarTitle({title: '在线客服'})
      this.setData({
        isGroupTalk: false,
        isCustomService: true
      });
      this.distributeServer().then(() => {
        this.userInfo = wx.getStorageSync('userInfo')
        this.isWorkingDuration();
        var sessionId = 'team-' + this.userInfo.server_room
        console.log('wx.nim', wx.nim)
        wx.nim.setCurrSession(sessionId)
        // var wholeSession = wx.getStorageSync(sessionId) // 拿到会话 
        // update 拒绝从缓存取数据，从服务器取 4/16
        var wholeSession
        var msgList
        cache.set('currentSessionId', sessionId)
        this.getMsgFromIMServer('team', this.userInfo.server_room).then(res => {
          console.log('拉取到在线客服消息', res)
          wholeSession = res;
          msgList = wholeSession.msgs;  // 拿到会话消息
          this.setData({
            avatar: '../../../resource/icon/default/kf-avatar.png',
            wholeSession: wholeSession,
            sessionId: sessionId,
            defOptions: getOptions(),
            msgList: this.msgListInit(msgList)
          });
          this.caculateDynamicHeight()
        });
      })
    } else {
      wx.nim.setCurrSession(options.id);
      // var wholeSession = wx.getStorageSync(options.id); // 拿到会话
      // update 拒绝从缓存取数据，从服务器取 4/16
      var wholeSession
      var msgList
      cache.set('currentSessionId', options.id);
      if (options.uid) { // 单聊
        this.role = 2;
        this.getMsgFromIMServer('p2p', options.to).then(res => {
          wholeSession = res;
          msgList = wholeSession.msgs;
          var list = cache.get('_p2p_userInfo_list');
          var currentP2p = list.filter(el => {
            return el.to == options.uid
          })[0];
          this.setData({
            isGroupTalk: false,
            avatar:currentP2p.avatar,
            wholeSession: wholeSession,
            sessionId: options.id,
            defOptions: getOptions(),
            msgList: this.msgListInit(msgList)
          });
          this.caculateDynamicHeight()
        })
      };

      if (options.teamId) { // 群聊
        this.role = 3;
        var list = cache.get('_team_patientInfo_list')
        var currentTeam = list.filter(el => {
          return el.to == options.teamId
        })[0]
        this.getTeamMembers(options.teamId).then(users => {
          console.log('getTeamMembers', users);
          this.teamMembers = users
          if (currentTeam.serverCustom && currentTeam.serverCustom.orderId) {
            this.setData({
              orderId: currentTeam.serverCustom.orderId
            })
            this.getOrderDetailByOrderId(currentTeam.serverCustom.orderId)
          }
          console.log('患者信息', currentTeam)
          console.log('currentTeam', currentTeam)
          this.getMsgFromIMServer('team',options.teamId).then(res => {
            console.log('新的群消息',res);
            wholeSession = res;
            msgList = wholeSession.msgs; // 拿到会话消息
            this.setData({
              isGroupTalk: true,
              cs: currentTeam.serverCustom,
              wholeSession: wholeSession,
              sessionId: options.id,
              defOptions: getOptions(),
              msgList: this.msgListInit(msgList)
            });
            this.caculateDynamicHeight()
          })
        })
      }
    }
    // 存储当前回合的sessionId
    // 更新会话的消息
    wx.eventBus.on('receive_msg', (params) => { // 文本
      console.log('params__', params);
      if (params.msg.type == 'notification' && params.msg.attach && params.msg.attach.type == 'updateTeam') {
        console.log('执行消息里面');
        console.log('this.data.sessionId', this.data.sessionId);
        var arr = cache.get('_finished_order_chat') || []
        arr.map(it => {
          if (it == this.data.sessionId) {
            this.setData({
              chatIsOver: true
            })
          }
        })
      }
      this.doneReceiveMsg (params)
    })
    wx.eventBus.on('receive_img', (params) => { // 图片
      this.doneReceiveMsg (params)
    })
    wx.eventBus.on('receive_file', (params) => { // 文件
      this.doneReceiveMsg (params)
    })
    this.createEmojiArr()
    console.log('-------------------')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
  },
  caculateDynamicHeight () {
    var me = this;
    setTimeout(function() {
      console.log('执行了重新触底行为')
       wx.createSelectorQuery().selectAll('#bottom').boundingClientRect(function(rects){
        rects.forEach(function(rect){
          console.log('动态计算高度',rect.bottom)
          me.setData({
            scrollTop: rect.bottom
          })
          me.caculated = true
          rect.id      // 节点的ID
          rect.dataset // 节点的dataset
          rect.left    // 节点的左边界坐标
          rect.right   // 节点的右边界坐标
          rect.top     // 节点的上边界坐标
          rect.bottom  // 节点的下边界坐标
          rect.width   // 节点的宽度
          rect.height  // 节点的高度
        })
      }).exec()     
     },100)

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onPageScroll: function (e) {
    currentScrollTop = e.detail ? e.detail.scrollTop : ''
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})